import sys
import json
import collections
import pandas as pd
import numpy as np

from matplotlib import pyplot as plt

with open(sys.argv[1]) as data_file:
  data = json.load(data_file)


stats = collections.defaultdict(list)
for info in data:
  ts = info['timestamp']
  info = info['data']
  if info['type'] == 'order':
    product = info['product']
    stats[product].append({
        'ts': ts,
        'rate_mean': info['rate_mean'],
        'rate_std': info['rate_std'],
        'rate_median': info['rate_median'],
        'p98': info['p98'],
        'p2': info['p2'],
    })


for product, info_list in stats.items():
  print(product)
  p_list = []
  p_list.append(product+'mean')
  p_list.append(product+'median')
  p_list.append(product+'p2')
  p_list.append(product+'p98')
  df = pd.DataFrame(info_list)
  df.ts = pd.DatetimeIndex(df.ts)
  plt.plot(df.ts, df.rate_mean)
  plt.plot(df.ts, df.rate_median)
  plt.plot(df.ts, df.p2)
  plt.plot(df.ts, df.p98)
  plt.legend(p_list)
  plt.show()

"""
p_list = []
for product, info_list in stats.items():
  p_list.append(product)
  df = pd.DataFrame(info_list)
  df.ts = pd.DatetimeIndex(df.ts)
  bp = df.rate_std / df.rate_mean
  p25 = np.percentile(bp, 25)
  p75 = np.percentile(bp, 75)
  print("%s: p25=%s, p75=%s", (product, p25, p75))
  plt.plot(df.ts, bp)
"""

plt.legend(p_list)
plt.show()
